package org.example.backend.util;

import com.alibaba.excel.EasyExcel;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * Excel导出工具类
 */
@Component
public class ExcelExportUtil {

    /**
     * 导出Excel
     *
     * @param response  响应
     * @param fileName  文件名
     * @param sheetName 工作表名
     * @param clazz     类型
     * @param data      数据
     * @param <T>       泛型
     * @throws IOException IO异常
     */
    public <T> void export(HttpServletResponse response, String fileName, String sheetName, Class<T> clazz, List<T> data) throws IOException {
        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        
        // 设置文件名
        String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + encodedFileName + ".xlsx");
        
        // 导出Excel
        EasyExcel.write(response.getOutputStream(), clazz)
                .sheet(sheetName)
                .doWrite(data);
    }
}